import authApi from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message,MessageBox,Notification } from 'element-ui'
import Code from '@/utils/code'

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    nick: '',
    introduction: '',
    visitor: false,
    roles: [],
    perms: [],
    setting: {
      articlePlatform: []
    },
    myRouters:[]
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_NICK: (state, nick) => {
      state.nick = nick
    },
    // SET_AVATAR: (state, avatar) => {
    //   state.avatar = avatar
    // },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMS: (state, perms) => {
      state.perms = perms
    },
    SET_VISITOR: (state, visitor) => {
      state.visitor = visitor
    },
    SET_MYROUTERS: (state, myRouters) => {
      state.myRouters = myRouters;
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        authApi.loginByUsername(username, userInfo.password).then(response => {
          const data = response.data;
          if (response.code == Code.SERVICE_FAIL){
            Notification({ title:'提示', message: response.message, type: 'error', duration: 5000});
          }
          commit('SET_TOKEN', data.token);
          setToken(response.data.token);
          // 昵称
          commit('SET_NICK', data.nickname);
          resolve();
        }).catch(error => {
          reject(error)
        })
      })
    },

    LogOutTest({ commit }){
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      removeToken();
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        authApi.logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

  }
}

export default user
